
package com.vietjetair.service;

import com.vietjetair.common.*;
import com.vietjetair.config.LogUtils;
import com.vietjetair.entity.AirTicket;
import com.vietjetair.vo.TicketVo;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.*;
import org.slf4j.Logger;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.sql.Driver;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import static java.lang.System.out;
import static java.lang.Thread.sleep;

/**
 * @author Administrator
 */
@Service("checkTicketService")
@PropertySource("classpath:properties/ticket.properties")
public class CheckTicketServiceImpl implements CheckTicketService {

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final static String ONE_WAY = "1";

    @Resource
    private RedisService redisService;

    private static Logger logger = LogUtils.getCheckTicketLogger();
    private static Logger exceptionLogger = LogUtils.getCheckTicketErrorLogger();

    private static final String PASSWORD = "123456789";
    private static final String GOON = "//a[text()='继续']";
    private static final String RN = "[\r\n]";
    private static final Map<String, String> urls;
    static
    {
        urls = new HashMap<>();
        urls.put("login", "https://booking.vietjetair.com/userprofilelogin.aspx?lang=zh");
        urls.put("reg", "https://booking.vietjetair.com/UserProfileRegistration.aspx?lang=zh");
        urls.put("home", "https://www.vietjetair.com/Sites/Web/zh-CN/Home");
    }



    /**
     * 注册用户
     */
    @Override
    public synchronized void registeredUserInformation(WebDriver driver) {
        long time = System.currentTimeMillis();
        logger.info(String.format("%s", OperationCodeEnum.REGISTERSTART.getText()));
        String email = null;
        try {
            //初始化打开浏览器
            driver = CommUtil.initialization();
            driver.get(urls.get("reg"));
            email = RandomInformation.getEmail(5, 15);
            String phone = RandomInformation.getTel();
            WebElement fax = new WebDriverWait(driver, 20, (long) 0.3).until(ExpectedConditions.presenceOfElementLocated(By.id("txtProfHFax")));
            //输入联系人信息
            //移动号码
            fax.sendKeys(phone);
            driver.findElement(By.id("lstPaxGender")).sendKeys("M");
            Select selectDestination = new Select(driver.findElement(By.id("lstPaxGender")));
            selectDestination.selectByValue("M");
            //名
            driver.findElement(By.id("txtProfFName")).sendKeys(RandomInformation.getLastName());
            //中间名和姓
            driver.findElement(By.id("txtProfLName")).sendKeys(RandomInformation.getTheName());
            //城市:
            driver.findElement(By.id("txtProfCity")).sendKeys("guangzhou");
            //地址
            driver.findElement(By.id("txtProfAddr1")).sendKeys("Oriental City Plaza, 190 Zhongshan Avenue West, Tianhe District, Guangzhou, Guangdong.");
            //电子邮件
            driver.findElement(By.id("txtProfEmail")).sendKeys(email);
            //密码1
            driver.findElement(By.id("txtProfUserPswd")).sendKeys(PASSWORD);
            //密码2
            driver.findElement(By.id("txtProfUserPswdConfirm")).sendKeys(PASSWORD);
            //地区
            Select select = new Select(driver.findElement(By.id("txtPax1_Ctry")));
            select.selectByValue("49");
            //省／州
            Select select1 = new Select(driver.findElement(By.id("txtPax1_Prov")));
            select1.selectByValue("10008");
            driver.findElement(By.xpath("//*[@id='UserRegistration']/table/tbody/tr[24]/td/table/tbody/tr/td[1]/a")).click();
            try {
                while (true) {
                    //获取Alert弹框对象；
                    Alert alertWindow = driver.switchTo().alert();
                    if (alertWindow==null){
                        break;
                    }
                    //点击alert弹出框中的确定按钮；
                    alertWindow.accept();
                    //移动号码
                    fax.sendKeys(phone);
                    driver.findElement(By.xpath("//*[@id='UserRegistration']/table/tbody/tr[24]/td/table/tbody/tr/td[1]/a")).click();
                    sleep(300);
                }
            } catch (NoAlertPresentException e) {
                out.println("尝试操作的alert弹出框未找到！");
            }
        } catch (Exception e) {
            exceptionLogger.error(String.format("%s%s", OperationCodeEnum.REGISTERERROR.getText(), e.getMessage()));
            return;
        }finally {
            CommUtil.quit(driver, OperationCodeEnum.REGISTEREND.getText() +"邮箱:"+email+",耗时:"+(System.currentTimeMillis()-time)/1000.0 );
        }
        //注册完成之后存入redis
        redisService.setListValue("emails",email);
    }


    /**
     * 用户登录
     * @param driver 驱动
     * @return 驱动
     */
    @Async
    @Override
    public WebDriver login(WebDriver driver) {
        long time = System.currentTimeMillis();
        List<String> emails = (List<String>) redisService.get("emails");
        if (emails == null || emails.isEmpty()) {
            registeredUserInformation(driver);
        }
        emails = (List<String>) redisService.get("emails");
        String mail = emails.get(emails.size() - 1);
        logger.info(OperationCodeEnum.LOGINSTART.getText() + ",邮箱:" + mail);
        try {
            driver.get(urls.get("login"));
            ElementUtil.intelligentWait(driver, 30, By.id("txtPublicUserID"));
            driver.findElement(By.id("txtPublicUserID")).sendKeys(mail);
            driver.findElement(By.id("txtPublicUserPswd")).sendKeys(PASSWORD);
            driver.findElement(By.xpath("//*[@id='PublicUserLogin']/table/tbody/tr[4]/td/table/tbody/tr/td[2]/a")).click();
            List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"PublicUserLogin\"]/p"));
            if (!elements.isEmpty()) {
                registeredUserInformation(driver);
                driver = CommUtil.initialization();
                driver.get(urls.get("login"));
                ElementUtil.intelligentWait(driver, 30, By.id("txtPublicUserID"));
                driver.findElement(By.id("txtPublicUserID")).sendKeys(mail);
                driver.findElement(By.id("txtPublicUserPswd")).sendKeys(PASSWORD);
                driver.findElement(By.xpath("//*[@id='PublicUserLogin']/table/tbody/tr[4]/td/table/tbody/tr/td[2]/a")).click();
            }
        } catch (Exception e) {
            exceptionLogger.error(String.format("%s%s", OperationCodeEnum.LOGINERROR.getText(), e));
        }finally {
            logger.info(String.format("%s,耗时:%s", OperationCodeEnum.LOGINEND.getText(), (System.currentTimeMillis() - time) / 1000.0));
        }
        return driver;
    }

    /**
     * 搜索航班
     * @param driver 驱动
     * @param vo 查询信息
     */
    @Async
    void searchFlights(WebDriver driver, TicketVo vo) {
        long time = System.currentTimeMillis();
        try {
            logger.info( OperationCodeEnum.SEARCHFLIGHTSSTART.getText());
            ElementUtil.intelligentWait(driver,60,By.id("departure1"));
            //将可读设为可写
            List<WebElement> inputs = driver.findElements(By.tagName("input"));
            for (WebElement input : inputs) {
                ((JavascriptExecutor) driver).executeScript("arguments[0].removeAttribute('readonly','readonly')",input);
            }
            sleep(300);
            //出发日期
            driver.findElement(By.id("departure1")).click();
            driver.findElement(By.id("departure1")).sendKeys(vo.getTxtDepartDateDay()+"/"+vo.getTxtDepartDateMonth()+"/2019");
            driver.findElement(By.id("chkRoundTrip1")).click();
            //单程or往返
            if (!vo.getTrip().equals(ONE_WAY)){
                driver.findElement(By.id("chkRoundTrip0")).click();
                //回来日期
                driver.findElement(By.id("departure2")).click();
                driver.findElement(By.id("departure2")).sendKeys(vo.getTxtReturnDateDay()+"/"+vo.getTxtReturnDateMonth()+"/2019");
            }
            //出发地
            Select startingPoint = new Select(driver.findElement(By.xpath("//select[@id='lstOrigAP']")));
            startingPoint.selectByValue(vo.getSelectOrigin());
            //目的地
            Select destination = new Select(driver.findElement(By.xpath("//select[@id='lstDestAP']")));
            destination.selectByValue(vo.getSelectDestination());
            //币种
            Select currency = new Select(driver.findElement(By.xpath("//select[@id='lstResCurrency']")));
            currency.selectByValue(vo.getCurrency());
            //大人
            driver.findElement(By.id("txtNumAdults")).clear();
            driver.findElement(By.id("txtNumAdults")).sendKeys(vo.getAdult());
            //儿童
            driver.findElement(By.id("txtNumChildren")).clear();
            driver.findElement(By.id("txtNumChildren")).sendKeys(vo.getChild());
            //婴儿
            driver.findElement(By.id("txtNumInfants")).clear();
            driver.findElement(By.id("txtNumInfants")).sendKeys(vo.getInfants());
            //搜索航班
            driver.findElement(By.xpath("//*[@id='right_side']/div[1]/div/table/tbody/tr[5]/td/table/tbody/tr/td/a[1]")).click();
        } catch (InterruptedException e) {
            e.printStackTrace();
            exceptionLogger.error(OperationCodeEnum.SEARCHFLIGHTSERROR.getText(),e);
        }finally {
            logger.info((String.format("%s,耗时:%s", OperationCodeEnum.SEARCHFLIGHTSEND.getText(), (System.currentTimeMillis() - time) / 1000.0)));
        }
    }

    /**
     * 测试方法ces
     */
    @Override
    public List<Map> priceChecking(TicketVo vo) {
        long time = System.currentTimeMillis();
        logger.info(OperationCodeEnum.CHECKFLIGHTSTART.getText());
        WebDriver driver = CommUtil.initialization();
        try {
            driver = login(driver);
            //搜索航班
            searchFlights(driver,vo);
            //获取价格返回
            return findTicket(driver, vo);
        }catch (Exception e){
            exceptionLogger.error(OperationCodeEnum.CHECKFLIGHTERROR.getText(),e.getMessage());
        }finally {
            CommUtil.quit(driver,OperationCodeEnum.CHECKFLIGHTEND.getText() + ",耗时:" + (System.currentTimeMillis() - time) / 1000.0 );
        }
        return null;
    }


    /**
     * 首页查询
     * @param vo 查询信息
     * @return 查询结果驱动
     */
    private WebDriver homeQuery(TicketVo vo) {
        WebDriver driver = CommUtil.initialization();
        driver.get(urls.get("home"));
        //查询表单数据
        WebElement form = driver.findElement(By.xpath("//form[@id='aspnetForm']"));
        //出发日
        Select selectOrigin = new Select(form.findElement(By.xpath("//select[@id='selectOrigin']")));
        selectOrigin.selectByValue(vo.getSelectOrigin());
        //出发日期
        WebElement txtDepartDate = form.findElement(By.xpath("//input[@id='ctl00_UcRightV31_TxtDepartDate']"));
        Actions actions = new Actions(driver);
        actions.moveToElement(txtDepartDate).click().perform();
        driver.findElement(By.xpath("//select[@class='ui-datepicker-month']")).sendKeys(vo.getTxtDepartDateMonth());
        if (!driver.findElements(By.xpath(String.format("//a[@class='ui-state-default' and text()='%s']", vo.getTxtDepartDateDay()))).isEmpty()){
            driver.findElement(By.xpath(String.format("//a[@class='ui-state-default' and text()='%s']", vo.getTxtDepartDateDay()))).click();
        }else if ((!driver.findElements(By.xpath(String.format("//a[@class='ui-state-default ui-state-highlight' and text()='%s']", vo.getTxtDepartDateDay()))).isEmpty())) {
            driver.findElement(By.xpath(String.format("//a[@class='ui-state-default ui-state-highlight' and text()='%s']", vo.getTxtDepartDateDay()))).click();
        }else if ((!driver.findElements(By.xpath(String.format("//a[@class='ui-state-default ui-state-active' and text()='%s']", vo.getTxtDepartDateDay()))).isEmpty())) {
            driver.findElement(By.xpath(String.format("//a[@class='ui-state-default ui-state-active' and text()='%s']", vo.getTxtDepartDateDay()))).click();
        }else if ((!driver.findElements(By.xpath(String.format("%s//a[@class='ui-state-default ui-state-highlight ui-state-active' and text()='']", vo.getTxtDepartDateDay()))).isEmpty())) {
            By.xpath(String.format("//a[@class='ui-state-default ui-state-highlight ui-state-active' and text()='%s']", vo.getTxtDepartDateDay())).findElement(driver).click();
        }
        //到达日
        Select selectDestination = new Select(form.findElement(By.xpath("//select[@id='selectDestination']")));
        selectDestination.selectByValue(vo.getSelectDestination());
        if (vo.getTrip().equals(ONE_WAY)) {
            form.findElement(By.xpath("//input[@id='ctl00_UcRightV31_RbOneWay']")).click();
        }else {
            form.findElement(By.xpath("//input[@id='ctl00_UcRightV31_RbRoundTrip']")).click();
            //回来日期
            WebElement txtReturnDate = form.findElement(By.xpath("//input[@id='ctl00_UcRightV31_TxtReturnDate']"));
            Actions actions1 = new Actions(driver);
            actions1.moveToElement(txtReturnDate).click().perform();
            driver.findElement(By.xpath("//select[@class='ui-datepicker-month']")).sendKeys(vo.getTxtReturnDateMonth());
            if (!By.xpath(String.format("//a[@class='ui-state-default' and text()='%s']", vo.getTxtReturnDateDay())).findElements(driver).isEmpty()){
                driver.findElement(By.xpath(String.format("//a[@class='ui-state-default' and text()='%s']", vo.getTxtReturnDateDay()))).click();
            }else if ((!driver.findElements(By.xpath(String.format("//a[@class='ui-state-default ui-state-highlight' and text()='%s']", vo.getTxtReturnDateDay()))).isEmpty())) {
                driver.findElement(By.xpath(String.format("//a[@class='ui-state-default ui-state-highlight' and text()='%s']", vo.getTxtReturnDateDay()))).click();
            }else if ((!driver.findElements(By.xpath(String.format("//a[@class='ui-state-default ui-state-active' and text()='%s']", vo.getTxtReturnDateDay()))).isEmpty())) {
                driver.findElement(By.xpath(String.format("//a[@class='ui-state-default ui-state-active' and text()='%s']", vo.getTxtReturnDateDay()))).click();
            }else if ((!driver.findElements(By.xpath(String.format("//a[@class='ui-state-default ui-state-highlight ui-state-active' and text()='%s']", vo.getTxtReturnDateDay()))).isEmpty())) {
                driver.findElement(By.xpath(String.format("//a[@class='ui-state-default ui-state-highlight ui-state-active' and text()='%s']", vo.getTxtReturnDateDay()))).click();
            }
        }
        driver.findElement(By.id("ctl00_UcHeaderV31_DrLang")).click();
        driver.findElement(By.id("ctl00_UcRightV31_RbENewsRegister")).click();
        form.findElement(By.xpath("//button[@id='ctl00_UcRightV31_CbbAdults_Button']")).click();
        form.findElement(By.xpath("//ul[@id='ctl00_UcRightV31_CbbAdults_OptionList']/li[text()="+vo.getAdult()+"]")).click();
        form.findElement(By.xpath("//button[@id='ctl00_UcRightV31_CbbChildren_Button']")).click();
        form.findElement(By.xpath("//ul[@id='ctl00_UcRightV31_CbbChildren_OptionList']/li[text()="+vo.getChild()+"]")).click();
        form.findElement(By.xpath("//button[@id='ctl00_UcRightV31_CbbInfants_Button']")).click();
        form.findElement(By.xpath("//ul[@id='ctl00_UcRightV31_CbbInfants_OptionList']/li[text()="+vo.getChild()+"]")).click();
        form.findElement(By.xpath("//input[@id='ctl00_UcRightV31_BtSearch']")).click();
        return driver;
    }

    /**
     * 扣位
     * @param vo 查询信息
     */
    @Async
    @Override
    public void fillInTheInformation(TicketVo vo) {
        long time = System.currentTimeMillis();
        logger.info(OperationCodeEnum.DEDUCTSTART.getText());
        StringBuilder sb = new StringBuilder();
        WebDriver driver = CommUtil.initialization();
        int parseInt=0;
        if (vo.getInfants()!=null) {
            parseInt = Integer.parseInt(vo.getInfants());
        }
        //扣位是否需要注册新账号
        registeredUserInformation(driver);
        try {
            //登录
            driver = login(driver);
            //搜索航班
            searchFlights(driver,vo);
            //初始化查询
            ElementUtil.intelligentWait(driver,20,By.id("toDepDiv"));
            JavascriptExecutor js = (JavascriptExecutor) driver;
            //隐藏悬浮提示 - 遮挡点击
            if (!vo.getTrip().equals(ONE_WAY)) {
                js.executeScript("for (var i=1;i<=10; i++){document.getElementById('fareRules'+i+'Box').style.display='none';} ");
            }else {
                js.executeScript("for (var i=1;i<=10; i++){document.getElementById('fareRules'+i+'Box').remove();} ");
            }
            if (By.xpath(String.format("//div[@id='toDepDiv']//input[@value='%s']", vo.getGoButton())).findElements(driver).isEmpty()){
                CommUtil.close(driver,"航班仓位变动!");
                return;
            }
            driver.findElement(By.xpath("//div[@id='toDepDiv']//input[@value='" + vo.getGoButton() + "']")).click();
            if (!vo.getTrip().equals(ONE_WAY)) {
                driver.findElement(By.xpath("//div[@id='toRetDiv']//input[@value='" + vo.getComButton() + "']")).click();
            }
            driver.findElement(By.xpath(GOON)).click();
            //多人
            int size = driver.findElements(By.xpath("//span[@class='FormLabel' and text()='主题:']")).size();
            for (int i = 1; i <= size; i++) {
                if (i==1){
                    if (CommUtil.ElementExist(driver,By.id("chkPax" + i + "_Infant")) && parseInt!=0){
                        driver.findElement(By.id("chkPax" + i + "_Infant")).click();
                        driver.findElement(By.id("txtPax" + i + "_Infant_FName")).sendKeys("myBaby");
                        driver.findElement(By.id("txtPax" + i + "_Infant_LName")).sendKeys("myBaby");
                        parseInt--;
                    }
                }else {
                    WebElement e1 = driver.findElement(By.id("txtPax" + i + "_Gender"));
                    String tagName = e1.getTagName();
                    if (!tagName.equals("input")) {
                        Select sel1 = new Select(e1);
                        sel1.selectByValue("M");
                    }
                    driver.findElement(By.id("txtPax" + i + "_LName")).sendKeys(RandomInformation.getTheName());
                    driver.findElement(By.id("txtPax" + i + "_FName")).sendKeys(RandomInformation.getLastName());
                    if (CommUtil.ElementExist(driver, By.id("chkPax" + i + "_Infant")) && parseInt!=0) {
                        driver.findElement(By.id("chkPax" + i + "_Infant")).click();
                        driver.findElement(By.id("txtPax" + i + "_Infant_FName")).sendKeys("myBaby");
                        driver.findElement(By.id("txtPax" + i + "_Infant_LName")).sendKeys("myBaby");
                        parseInt--;
                    }
                }
            }
            driver.findElement(By.xpath(GOON)).click();
            WebElement webElement = new WebDriverWait(driver, 60, (long) 0.3).until(ExpectedConditions.presenceOfElementLocated(By.id("tabhdr2")));
            logger.info(driver.findElement(By.id("tabhdr2")).getText());
            sb.append("乘坐:").append(driver.findElement(By.id("tabhdr2")).getText());
            //去程位置数
            int s = 0;
            //回程位置数
            int r = 0;
            boolean departureSeat = false;
            boolean returnSeat = false;
            webElement.click();
            // 选择位置
            for (int i = 0; i < 40; i++) {
                for (int j = 0; j <= 6; j++) {
                    driver.findElement(By.xpath("//div[@id='m1rp" + i + "sp"+j+"i']")).click();
                    String url1 = driver.findElement(By.id("m1rp" + i + "sp"+j+"i")).getAttribute("style");
                    String substring = url1.substring(url1.indexOf("/") + 1, url1.indexOf("/") + 18);
                    if ("Seat-selected.png".equals(substring)) {
                        List<WebElement> elements = driver.findElements(By.xpath("//div[@id='m2rp" + i + "sp" + j + "i']"));
                        if (elements.isEmpty()){
                            continue;
                        }
                        WebElement seat = elements.get(0);
                        String seatspan = seat.findElement(By.className("seatspan")).getText();
                        s++;
                        sb.append(",用户").append(s).append(",去程位置:").append("m1rp").append(i).append("sp").append(j).append("i ->").append(seatspan);
                        logger.info(String.format("锁定去程位置:m1rp%dsp%di  -> %s", i, j, seatspan));
                        departureSeat = true;
                        if (s==size){
                            break;
                        }
                    }
                }
                //如果选中退出
                if (departureSeat && size==s){
                    break;
                }
            }
            /*//截图
            screenshot(driver);*/
            //往返的话选择回程机票
            if (!vo.getTrip().equals(ONE_WAY)) {
                sb.append("\n").append(",回程").append(driver.findElement(By.id("tabhdr3")).getText()).append("\n");
                //回程航班
                driver.findElement(By.id("tab3")).click();
                for (int i = 0; i < 40; i++) {
                    for (int j = 0; j <= 6; j++) {
                        List<WebElement> driverElements = driver.findElements(By.xpath("//div[@id='m2rp" + i + "sp" + j + "i']"));
                        if(driverElements.isEmpty()){
                            continue;
                        }
                        driverElements.get(0).click();
                        String url1 = driver.findElement(By.id("m2rp" + i + "sp"+j+"i")).getAttribute("style");
                        String substring1 = url1.substring(url1.indexOf("/") + 1, url1.indexOf("/") + 18);
                        if ("Seat-selected.png".equals(substring1)) {
                            List<WebElement> elements = driver.findElements(By.xpath("//div[@id='m2rp" + i + "sp" + j + "i']"));
                            if (elements.isEmpty()){
                                continue;
                            }
                            WebElement seat = elements.get(0);
                            seat.click();
                            String seatspan = seat.findElement(By.className("seatspan")).getText();
                            r++;
                            logger.info(String.format("锁定回程位置:m2rp%dsp%di  -> %s", i, j,seatspan));
                            sb.append(",用户").append(s).append(",回程位置:").append("m1rp").append(i).append("sp").append(j).append("i ->").append(seatspan);
                            returnSeat = true;
                            if (r==size){
                                break;
                            }
                        }
                    }
                    if (returnSeat && size==r) {
                        break;
                    }
                }
            }
            if (!vo.getTrip().equals(ONE_WAY)) {
                if(!departureSeat || !returnSeat){
                    CommUtil.quit(driver,"来或去无座位");
                    return;
                }
            }else{
                if(!departureSeat){
                    CommUtil.quit(driver,"无座位");
                    return;
                }
            }
            driver.findElement(By.xpath("//div[@id='mainTabs']/ul/li[2]/a")).click();
            List<WebElement> lstShopSelect = driver.findElements(By.className("lstShopSelect"));
            for (WebElement element : lstShopSelect) {
                Select select = new Select(element);
                select.selectByIndex(0);
            }
            List<WebElement> priorityCheckinNoThanks = driver.findElements(By.className("priorityCheckinNoThanks"));
            for (WebElement priorityCheckinNoThank : priorityCheckinNoThanks) {
                if (priorityCheckinNoThank.isDisplayed()){
                    priorityCheckinNoThank.click();
                }
            }
            By.xpath(GOON).findElement(driver).click();
            WebElement logo = new WebDriverWait(driver, 20, (long) 0.3).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//img[@src='images/UPOPlogo.png']")));
            logo.click();
            driver.findElement(By.id("dangerous_goods_check")).click();
            By.xpath(GOON).findElement(driver).click();
            WebElement close = new WebDriverWait(driver, 20, (long) 0.3).until(ExpectedConditions.presenceOfElementLocated(By.className("close")));
            close.click();
            driver.findElement(By.id("chkIAgree")).click();
            driver.findElement(By.xpath("//*[@id='tblBackCont']/tbody/tr/td[2]/a")).click();
            sleep(15000);
            if (!driver.findElements(By.xpath("//*[@id='itin']/p")).isEmpty()) {
                String text = driver.findElement(By.xpath("//*[@id='itin']/p")).getText();
                logger.error(text);
            }
            String currentUrl = driver.getCurrentUrl();
            String orderNo = driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/p[2]")).getText();
            String money = driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/p[1]/em[1]")).getText();
            String currency = driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[2]/div[1]/p[3]")).getText().replaceAll(RN, "");
            String date = driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[2]/div[1]/p[1]")).getText();
            String name = driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/p[3]")).getText().replaceAll(RN, "");
            String outTime = driver.findElement(By.id("orderTimeoutTips_note")).getText().replaceAll(RN, "");
            String a = "由:"+vo.getSelectOrigin()+",飞往:"+vo.getSelectDestination()+",的机票预订成功!基本信息如下:\n";
            sb.insert(0,a);
            sb.append("\n支付订单编号:").append(orderNo).append(",支付金额:").append(money).append(",").append(currency)
                    .append(",交易时间:").append(date).append("\n").append(name)
                    .append(",支付过期时间:").append(outTime).append(",支付地址:").append(currentUrl);
            logger.info(sb.toString());
            out.println(sb.toString());
            CommUtil.quit(driver, OperationCodeEnum.DEDUCTEND.getText()+"耗时:"+(System.currentTimeMillis()-time)/1000.0 );
        } catch (Exception e) {
            exceptionLogger.error(String.format("%s%s", OperationCodeEnum.DEDUCTERROR.getText(), e));
        }
    }


    /**
     * 查价
     * @param vo 查询信息
     * @return 查询结果信息
     */
    @Override
    public List<Map> findTicket(WebDriver driver,TicketVo vo) {
        long time = System.currentTimeMillis();
        logger.info( OperationCodeEnum.CHECKPRICESTART.getText());
        List<Map> map = null;
        try {
            ElementUtil.intelligentWait(driver,20,By.id("toDepDiv"));
            List<WebElement> departureFlight = driver.findElements(By.xpath("//div[@id='toDepDiv']//table[@class='FlightsGrid']/tbody/tr[position() mod 2 = 1]"));
            List<WebElement> roundTripFlight = driver.findElements(By.xpath("//div[@id='toRetDiv']//table[@class='FlightsGrid']/tbody/tr[position() mod 2 = 1]"));
            map = new ArrayList<>();
            Map<Integer, AirTicket> departureList = new HashMap<>();
            Map<Integer, AirTicket> roundTripList = new HashMap<>();
            getThePrice(vo,departureFlight,departureList);
            if (!vo.getTrip().equals(ONE_WAY)) {
                getThePrice(vo, roundTripFlight, roundTripList);
            }
            map.add(departureList);
            map.add(roundTripList);
        } catch (Exception e) {
            exceptionLogger.error(String.format("%s%s", OperationCodeEnum.CHECKPRICEERROR.getText(), e));
        }finally {
            logger.info(OperationCodeEnum.CHECKPRICEEND.getText()+"耗时:"+(System.currentTimeMillis()-time)/1000.0 );
        }
        return map;
    }

    /**
     * 拿取航班价格信息
     * @param vo 查询信息
     * @param roundTripFlight 信息节点集
     * @param roundTripList 转换结果集
     */
    private void getThePrice(TicketVo vo, List<WebElement> roundTripFlight, Map<Integer, AirTicket> roundTripList) {
        try {
            if (null != roundTripFlight && !roundTripFlight.isEmpty()) {
                for (int i = 0; i < roundTripFlight.size(); i++) {
                    WebElement webElement = roundTripFlight.get(i);
                    boolean soldOut = webElement.findElements(By.xpath("./td[2]//tr[1]/td[1]/div[@class='ErrorCaption']")).isEmpty();
                    if (soldOut) {
                        AirTicket ticket = new AirTicket();
                        String flightDate = webElement.findElement(By.xpath("./td[1]//tr[1]/td[1]")).getText().replaceAll(RN, "");
                        String departureTime = webElement.findElement(By.xpath("./td[1]//tr[1]/td[2]")).getText().replaceAll(RN, "");
                        String timeOfArrival = webElement.findElement(By.xpath("./td[1]//tr[1]/td[3]")).getText().replaceAll(RN, "");
                        String flightDetails = webElement.findElement(By.xpath("./td[1]//tr[1]/td[4]")).getText().replaceAll(RN, "");
                        boolean isPromo = !webElement.findElements(By.xpath("./td[2]/table/tbody/tr[1]/td[1]/input[@id='fare']")).isEmpty();
                        boolean isEco = !webElement.findElements(By.xpath("./td[2]/table/tbody/tr[1]/td[2]/input[@id='fare']")).isEmpty();
                        boolean isSkyBoss = !webElement.findElements(By.xpath("./td[2]/table/tbody/tr[1]/td[3]/input[@id='fare']")).isEmpty();
                        if (isPromo) {
                            AirTicket.Promo promo = new AirTicket.Promo();
                            String fare = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[1]/input[@id='fare']")).getAttribute("value").replaceAll(RN, "");
                            String fareTaxes = webElement.findElement(By.xpath("./td[2]/table//tr[1]//td[1]/input[@id='fare_taxes']")).getAttribute("value").replaceAll(RN, "");
                            String total = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[1]/input[@id='total_complete_charges']")).getAttribute("value").replaceAll(RN, "");
                            String charges = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[1]/input[@id='charges']")).getAttribute("value").replaceAll(RN, "");
                            String idKey = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[1]/input[@type='radio']")).getAttribute("value");
                            promo.setCharges(charges);
                            promo.setFare(fare);
                            promo.setTotal(total);
                            promo.setComeButton(idKey);
                            promo.setFareTaxes(fareTaxes);
                            promo.setGoButton(idKey);
                            ticket.setPromo(promo);
                        }
                        if (isEco) {
                            AirTicket.Eco eco = new AirTicket.Eco();
                            String fare = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[2]/input[@id='fare']")).getAttribute("value").replaceAll(RN, "");
                            String fareTaxes = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[2]/input[@id='fare_taxes']")).getAttribute("value").replaceAll(RN, "");
                            String total = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[2]/input[@id='total_complete_charges']")).getAttribute("value").replaceAll(RN, "");
                            String charges = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[2]/input[@id='charges']")).getAttribute("value").replaceAll(RN, "");
                            String idKey = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[2]/input[@type='radio']")).getAttribute("value");
                            eco.setCharges(charges);
                            eco.setFare(fare);
                            eco.setTotal(total);
                            eco.setFareTaxes(fareTaxes);
                            eco.setComeButton(idKey);
                            eco.setGoButton(idKey);
                            ticket.setEco(eco);
                        }
                        if (isSkyBoss) {
                            AirTicket.SkyBoss skyBoss = new AirTicket.SkyBoss();
                            String fare = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[3]/input[@id='fare']")).getAttribute("value").replaceAll(RN, "");
                            String fareTaxes = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[3]/input[@id='fare_taxes']")).getAttribute("value").replaceAll(RN, "");
                            String total = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[3]/input[@id='total_complete_charges']")).getAttribute("value").replaceAll(RN, "");
                            String charges = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[3]/input[@id='charges']")).getAttribute("value").replaceAll(RN, "");
                            String idKey = webElement.findElement(By.xpath("./td[2]/table//tr[1]/td[3]/input[@type='radio']")).getAttribute("value");
                            skyBoss.setCharges(charges);
                            skyBoss.setFare(fare);
                            skyBoss.setTotal(total);
                            skyBoss.setFareTaxes(fareTaxes);
                            skyBoss.setComeButton(idKey);
                            skyBoss.setGoButton(idKey);
                            ticket.setSkyBoss(skyBoss);
                        }
                        ticket.setDepartureTime(departureTime);
                        ticket.setFlightDate(flightDate);
                        ticket.setFlightDetails(flightDetails);
                        ticket.setTimeOfArrival(timeOfArrival);
                        ticket.setKey(vo.getKey());
                        out.println(ticket.toString());
                        roundTripList.put(i, ticket);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void screenshot(WebDriver driver) {
        // 调用截图方法
        File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        JavascriptExecutor jse = (JavascriptExecutor) driver;
        //y value '250' can be altered
        jse.executeScript("scroll(0, 250)");
        try {
            org.apache.commons.io.FileUtils.copyFile(file, new File("D:\\hello.png"));
        } catch (IOException e) {
            CommUtil.close(driver, e.getMessage());
        }
    }

    @Override
    public void test() {
        WebDriver driver = CommUtil.initialization();
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

        driver.get("http://www.baidu.com/");
        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //在新标签页打开新的链接全部代码（Google到的）：

        String baseUrl = "http://www.google.co.uk/";

        JavascriptExecutor js = (JavascriptExecutor)driver;
        driver.navigate().to(baseUrl);
        js.executeScript("window.open()");
        ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(1));
        driver.navigate().to("http://www.baidu.com/");
        driver.navigate().to(baseUrl);
        js.executeScript("window.open()");
        ArrayList<String> tabs1 = new ArrayList<String>(driver.getWindowHandles());
        out.println(tabs.size());
        out.println(tabs1.size());
        driver.switchTo().window(tabs1.get(2));
        driver.navigate().to("http://www.baidu.com/");
        js.executeScript("window.close();");
        driver.switchTo().window(tabs1.get(1));
        js.executeScript("window.close();");
        driver.switchTo().window(tabs1.get(0));
        js.executeScript("window.close();");
/*
        ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());

        driver.switchTo().window(tabs.get(1)); //switches to new tab

        driver.get("https://www.facebook.com");



        driver.switchTo().window(tabs.get(0)); // switch back to main screen

        driver.get("https://www.news.google.com");*/
    }

}